<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>服务分类列表</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            overflow-x: hidden;
        }

        /* 自定义滚动条样式 - 绿色主题 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb {
            background: #3d8944;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #2d7a30;
        }

        /* Firefox 滚动条样式 */
        * {
            scrollbar-width: thin;
            scrollbar-color: #3d8944 #f1f1f1;
        }

        .container {
            height: 100vh;
            display: flex;
            flex-direction: column;
            background: #fff;
        }

        /* 一级分类 Tabs */
        .tabs-container {
            width: 100%;
            background: #fff;
            border-bottom: 1px solid #eee;
            overflow-x: auto;
            white-space: nowrap;
            padding: 0 10px;
            flex-shrink: 0;
        }

        .tabs-container::-webkit-scrollbar {
            display: none;
        }

        .tab-item {
            display: inline-block;
            padding: 12px 20px;
            margin-right: 20px;
            font-size: 16px;
            color: #666;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s;
        }

        .tab-item.active {
            color: #3d8944;
            font-weight: bold;
            border-bottom-color: #3d8944;
        }

        /* 内容区域 */
        .content-area {
            flex: 1;
            display: flex;
            overflow: hidden;
        }

        /* 左侧二级分类 */
        .left-sidebar {
            width: 100px;
            background: #f8f8f8;
            overflow-y: auto;
            flex-shrink: 0;
        }

        .category-item {
            height: 60px;
            display: flex;
            align-items: center;
            padding: 0 12px;
            font-size: 14px;
            color: #666;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: all 0.3s;
        }

        .category-item.active {
            background: #fff;
            color: #3d8944;
            font-weight: bold;
        }

        /* 右侧内容 */
        .right-content {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #fff;
        }

        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #999;
            font-size: 14px;
        }

        /* 三级分类按钮 */
        .level3-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 30px;
        }

        .level3-btn {
            padding: 8px 16px;
            font-size: 14px;
            border: 1px solid #ddd;
            border-radius: 20px;
            background: #fff;
            color: #666;
            cursor: pointer;
            transition: all 0.3s;
        }

        .level3-btn.active {
            background: #3d8944;
            color: #fff;
            border-color: #3d8944;
        }

        /* 四级分类商品列表 */
        .goods-list {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .goods-item {
            display: flex;
            gap: 12px;
            padding: 12px;
            background: #f9f9f9;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .goods-item:active {
            background: #f0f0f0;
        }

        .goods-image {
            width: 80px;
            height: 80px;
            border-radius: 8px;
            background: #e0e0e0;
            object-fit: cover;
            flex-shrink: 0;
        }

        .goods-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 6px;
            overflow: hidden;
        }

        .goods-code {
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
        }

        .goods-name {
            font-size: 14px;
            color: #333;
            font-weight: 500;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            margin-bottom: 6px;
        }

        .goods-price {
            font-size: 16px;
            color: #3d8944;
            font-weight: bold;
        }

        .loading {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            color: #999;
            font-size: 14px;
        }

        .loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #3d8944;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 8px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .error {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            color: #3d8944;
            font-size: 14px;
        }

        /* 遮罩层 loading */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            flex-direction: column;
            gap: 12px;
        }

        .loading-overlay.hidden {
            display: none;
        }

        .loading-overlay-text {
            color: #3d8944;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 一级分类 Tabs -->
        <div class="tabs-container" id="tabsContainer">
            <div class="loading">
                <div class="loading-spinner"></div>
                加载中...
            </div>
        </div>

        <!-- 内容区域 -->
        <div class="content-area">
            <!-- 左侧二级分类 -->
            <div class="left-sidebar" id="leftSidebar">
                <div class="empty-state">请选择一级分类</div>
            </div>

            <!-- 右侧内容 -->
            <div class="right-content" id="rightContent">
                <div class="empty-state">暂无数据</div>
            </div>
        </div>
    </div>

    <!-- 全局 Loading 遮罩层 -->
    <div class="loading-overlay hidden" id="loadingOverlay">
        <div class="loading-spinner" style="width: 32px; height: 32px; border-width: 3px; margin-right: 0;"></div>
        <div class="loading-overlay-text">加载中...</div>
    </div>

    <script>
        // 配置
        const API_BASE_URL = 'https://anfine.huasun-healthcare.com/api-ah';
        const IMAGE_BASE_URL = 'https://anfine.huasun-healthcare.com/api';
        
        // 从 URL 参数获取参数
        const urlParams = new URLSearchParams(window.location.search);
        const hospital = urlParams.get('hospital') || urlParams.get('hospitalId') || '1';
        const token = urlParams.get('token') || '';
        const sysOrgCode = urlParams.get('sys_org_code') || urlParams.get('sysOrgCode') || 'A01A03A01';

        // 图片路径处理函数（参考项目中的 useImage）
        function useImage(url) {
            if (!url) {
                return '';
            }
            // 如果已经是完整 URL，直接返回
            if (url.startsWith('http://') || url.startsWith('https://')) {
                return url;
            }
            // 处理相对路径，拼接完整 URL
            const temp = url.split(',')[0] || '';
            return `${IMAGE_BASE_URL}/sys/common/static/${temp}`;
        }

        // Loading 显示/隐藏函数
        function showLoading(text = '加载中...') {
            const overlay = document.getElementById('loadingOverlay');
            if (overlay) {
                const textEl = overlay.querySelector('.loading-overlay-text');
                if (textEl) {
                    textEl.textContent = text;
                }
                overlay.classList.remove('hidden');
            }
        }

        function hideLoading() {
            const overlay = document.getElementById('loadingOverlay');
            if (overlay) {
                overlay.classList.add('hidden');
            }
        }

        // 显示区域 loading（用于特定区域）
        function showAreaLoading(containerId, text = '加载中...') {
            const container = document.getElementById(containerId);
            if (container) {
                container.innerHTML = `<div class="loading"><div class="loading-spinner"></div>${text}</div>`;
            }
        }
        
        // 状态管理
        const state = {
            typeList: [],           // 一级分类列表
            act1: null,             // 当前选中的一级分类
            cateList2: [],          // 二级分类列表
            act2: null,             // 当前选中的二级分类
            cateList3: [],          // 三级分类列表
            act3: null,             // 当前选中的三级分类
            cateList4: [],          // 四级分类（商品）列表
            validate: '0'           // 验证状态
        };

        // 获取请求头
        function getRequestHeaders() {
            const headers = {
                'Content-Type': 'application/json'
            };
            
            // 添加 token
            if (token) {
                headers['X-Access-Token'] = token;
            }
            
            // 添加 sys_org_code
            if (sysOrgCode) {
                headers['sys_org_code'] = sysOrgCode;
            }
            
            return headers;
        }

        // API 请求封装
        async function request(url, params = {}) {
            try {
                const queryString = new URLSearchParams(params).toString();
                const fullUrl = `${API_BASE_URL}${url}${queryString ? '?' + queryString : ''}`;
                
                const response = await fetch(fullUrl, {
                    method: 'GET',
                    headers: getRequestHeaders(),
                    credentials: 'include'
                });
                
                const data = await response.json();
                
                // 处理 401 错误 - Token失效
                if (data.code === 401) {
                    return { 
                        error: data.message || 'Token失效，请重新登录!', 
                        success: null,
                        errorCode: 401
                    };
                }
                
                if (data.code === 200 || data.code === 0) {
                    return { error: null, success: data.result || data.success || data };
                } else {
                    return { error: data.message || '请求失败', success: null };
                }
            } catch (error) {
                console.error('请求失败:', error);
                return { error: error.message || '网络错误', success: null };
            }
        }

        // 获取一级分类列表
        async function getServiceVisibleList() {
            showAreaLoading('tabsContainer', '加载中...');
            
            const { error, success, errorCode } = await request('/service_visible/serviceVisible/list', {
                hospitalId: hospital
            });
            
            // 处理 token 失效
            if (errorCode === 401) {
                document.getElementById('tabsContainer').innerHTML = `<div class="error">${error || 'Token失效，请重新登录!'}</div>`;
                return;
            }
            
            if (error || !success || !success.records || success.records.length === 0) {
                document.getElementById('tabsContainer').innerHTML = '<div class="error">未配置一级分类或请求失败</div>';
                return;
            }
            
            const record = success.records[0];
            const mode = record.mode || '';
            const modeDictText = record.mode_dictText || '';
            
            if (!mode) return;
            
            const modeList = mode.split(',');
            const modeTextList = modeDictText.split(',');
            
            state.typeList = modeList.map((item, index) => ({
                itemText: modeTextList[index] || item,
                itemValue: item
            }));
            
            if (state.typeList.length > 0) {
                state.act1 = state.typeList[0].itemValue;
                renderTabs();
                getCate2Data();
            }
        }

        // 获取二级分类数据
        async function getCate2Data() {
            if (!state.act1) return;
            
            showLoading('加载分类数据...');
            showAreaLoading('leftSidebar', '加载中...');
            showAreaLoading('rightContent', '加载中...');
            
            const { error, success } = await request('/nurse_goods/nurseGoods/listByWeChat', {
                pid: '0',
                nurse_type: state.act1,
                hospital: hospital
            });
            
            hideLoading();
            
            if (error || !success) {
                renderLeftSidebar([]);
                renderRightContent([]);
                return;
            }
            
            state.cateList2 = success || [];
            
            if (state.cateList2.length > 0) {
                const firstItem = state.cateList2[0];
                state.act2 = firstItem.key || firstItem.id;
                renderLeftSidebar(state.cateList2);
                getCate3Data();
            } else {
                state.act2 = null;
                state.cateList3 = [];
                state.cateList4 = [];
                renderLeftSidebar([]);
                renderRightContent([]);
            }
        }

        // 获取三级分类数据
        async function getCate3Data() {
            if (!state.act2) {
                state.cateList3 = [];
                state.cateList4 = [];
                state.act3 = null;
                renderRightContent([]);
                return;
            }
            
            showLoading('加载分类数据...');
            showAreaLoading('rightContent', '加载中...');
            
            const { error, success } = await request('/nurse_goods_detail/nurseGoodsDetail/queryListNew', {
                pid: String(state.act2)
            });
            
            hideLoading();
            
            if (error || !success) {
                state.cateList3 = [];
                state.cateList4 = [];
                renderRightContent([]);
                return;
            }
            
            state.cateList3 = success || [];
            
            if (state.cateList3.length > 0) {
                state.act3 = state.cateList3[0].id;
                renderRightContent(state.cateList3);
                getCate4Data();
            } else {
                state.act3 = null;
                state.cateList4 = [];
                renderRightContent([]);
            }
        }

        // 获取四级分类（商品）数据
        async function getCate4Data() {
            if (!state.act3) {
                state.cateList4 = [];
                renderGoodsList([]);
                return;
            }
            
            showLoading('加载商品数据...');
            const goodsListEl = document.getElementById('goodsList');
            if (goodsListEl) {
                goodsListEl.innerHTML = '<div class="loading"><div class="loading-spinner"></div>加载中...</div>';
            }
            
            const { error, success } = await request('/nurse_goods_detail/nurseGoodsDetail/queryListNew', {
                pid: String(state.act3)
            });
            
            hideLoading();
            
            if (error || !success) {
                state.cateList4 = [];
                renderGoodsList([]);
                return;
            }
            
            state.cateList4 = success || [];
            renderGoodsList(state.cateList4);
        }

        // 渲染一级分类 Tabs
        function renderTabs() {
            const container = document.getElementById('tabsContainer');
            if (!state.typeList || state.typeList.length === 0) {
                container.innerHTML = '<div class="error">暂无分类</div>';
                return;
            }
            
            container.innerHTML = state.typeList.map(item => 
                `<div class="tab-item ${state.act1 == item.itemValue ? 'active' : ''}" 
                      data-value="${item.itemValue}">
                    ${item.itemText}
                 </div>`
            ).join('');
            
            // 绑定点击事件
            container.querySelectorAll('.tab-item').forEach(item => {
                item.addEventListener('click', () => {
                    const value = item.getAttribute('data-value');
                    if (state.act1 === value) return; // 如果已选中，不重复加载
                    state.act1 = value;
                    renderTabs();
                    getCate2Data();
                });
            });
        }

        // 渲染左侧二级分类
        function renderLeftSidebar(list) {
            const sidebar = document.getElementById('leftSidebar');
            if (!list || list.length === 0) {
                sidebar.innerHTML = '<div class="empty-state">暂无数据</div>';
                return;
            }
            
            sidebar.innerHTML = list.map(item => {
                const id = item.key || item.id;
                const name = item.title || item.type_name || '';
                return `<div class="category-item ${state.act2 == id ? 'active' : ''}" 
                            data-id="${id}">
                            ${name}
                        </div>`;
            }).join('');
            
            // 绑定点击事件
            sidebar.querySelectorAll('.category-item').forEach(item => {
                item.addEventListener('click', () => {
                    const id = item.getAttribute('data-id');
                    if (state.act2 === id) return; // 如果已选中，不重复加载
                    state.act2 = id;
                    renderLeftSidebar(state.cateList2);
                    getCate3Data();
                });
            });
        }

        // 渲染右侧内容（三级分类和商品列表）
        function renderRightContent(level3List) {
            const content = document.getElementById('rightContent');
            
            if (!level3List || level3List.length === 0) {
                content.innerHTML = '<div class="empty-state">暂无数据</div>';
                return;
            }
            
            let html = '<div class="level3-buttons">';
            html += level3List.map(item => 
                `<div class="level3-btn ${state.act3 == item.id ? 'active' : ''}" 
                      data-id="${item.id}">
                    ${item.type_name || item.typeName || ''}
                 </div>`
            ).join('');
            html += '</div>';
            
            // 商品列表区域
            html += '<div class="goods-list" id="goodsList"></div>';
            
            content.innerHTML = html;
            
            // 绑定三级分类按钮点击事件
            content.querySelectorAll('.level3-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const id = btn.getAttribute('data-id');
                    if (state.act3 === id) return; // 如果已选中，不重复加载
                    state.act3 = id;
                    renderRightContent(state.cateList3);
                    getCate4Data();
                });
            });
            
            // 渲染商品列表
            renderGoodsList(state.cateList4);
        }

        // 渲染商品列表
        function renderGoodsList(goodsList) {
            const goodsListEl = document.getElementById('goodsList');
            if (!goodsListEl) return;
            
            if (!goodsList || goodsList.length === 0) {
                goodsListEl.innerHTML = '<div class="empty-state">暂无商品</div>';
                return;
            }
            
            goodsListEl.innerHTML = goodsList.map(item => {
                const picUrl = item.pic || '';
                const imageUrl = useImage(picUrl); // 使用 useImage 处理图片路径
                const name = item.goods_name || item.type_name || item.typeName || '';
                const price = state.validate == '0' ? (item.price || 0) : (item.pricenew || item.price || 0);
                // 服务项目编号：可能存在于多个字段中
                const serviceNo = item.goods_code || item.code || item.serviceNo || item.service_code || item.goodsNo || '';
                
                return `<div class="goods-item" data-id="${item.id}">
                    ${picUrl ? `<img src="${imageUrl}" class="goods-image" alt="${name}" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2280%22 height=%2280%22%3E%3Crect fill=%22%23e0e0e0%22 width=%2280%22 height=%2280%22/%3E%3Ctext x=%2250%25%22 y=%2250%25%22 text-anchor=%22middle%22 dy=%22.3em%22 fill=%22%23999%22 font-size=%2212%22%3E无图%3C/text%3E%3C/svg%3E'">` : '<div class="goods-image"></div>'}
                    <div class="goods-info">
                        ${serviceNo ? `<div class="goods-code">服务项目编号：${serviceNo}</div>` : ''}
                        <div class="goods-name">${name}</div>
                        <div class="goods-price">预收价格：¥${price}</div>
                    </div>
                </div>`;
            }).join('');
            
            // 绑定商品点击事件（可以跳转到详情页）
            goodsListEl.querySelectorAll('.goods-item').forEach(item => {
                item.addEventListener('click', () => {
                    const id = item.getAttribute('data-id');
                    // 可以在这里添加跳转逻辑
                    console.log('点击商品:', id);
                    // 例如：window.location.href = `/goods-detail.html?id=${id}`;
                });
            });
        }

        // 初始化
        async function init() {
            // 检查 token
            if (!token) {
                document.getElementById('tabsContainer').innerHTML = '<div class="error">缺少 token 参数，请在 URL 中添加 ?token=xxx</div>';
                return;
            }
            
            await getServiceVisibleList();
        }

        // 页面加载完成后初始化
        window.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>

